package com.ruoyi.system.service.manager.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.shell.ShellUtil;
import com.ruoyi.system.domain.manager.DevService;
import com.ruoyi.system.mapper.manager.DevServiceMapper;
import com.ruoyi.system.service.manager.IDevServiceService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * 服务列Service业务层处理
 *
 * @author ruoyi
 * @date 2024-03-26
 */
@Service
public class DevServiceServiceImpl implements IDevServiceService {
    @Resource
    private DevServiceMapper devServiceMapper;

    /**
     * 查询服务列
     *
     * @param id 服务列主键
     * @return 服务列
     */
    @Override
    public DevService selectDevServiceById(Long id) {
        return devServiceMapper.selectDevServiceById(id);
    }

    /**
     * 查询服务列列表
     *
     * @param devService 服务列
     * @return 服务列
     */
    @Override
    public List<DevService> selectDevServiceList(DevService devService) {
        return devServiceMapper.selectDevServiceList(devService);
    }

    /**
     * 新增服务列
     *
     * @param devService 服务列
     * @return 结果
     */
    @Override
    public int insertDevService(DevService devService) {
        devService.setCreateTime(DateUtils.getNowDate());
        return devServiceMapper.insertDevService(devService);
    }

    /**
     * 修改服务列
     *
     * @param devService 服务列
     * @return 结果
     */
    @Override
    public int updateDevService(DevService devService) {
        devService.setUpdateTime(DateUtils.getNowDate());
        return devServiceMapper.updateDevService(devService);
    }

    /**
     * 批量删除服务列
     *
     * @param ids 需要删除的服务列主键
     * @return 结果
     */
    @Override
    public int deleteDevServiceByIds(Long[] ids) {
        return devServiceMapper.deleteDevServiceByIds(ids);
    }

    /**
     * 删除服务列信息
     *
     * @param id 服务列主键
     * @return 结果
     */
    @Override
    public int deleteDevServiceById(Long id) {
        return devServiceMapper.deleteDevServiceById(id);
    }

    @Override
    public AjaxResult restartService(Long id) {
        DevService devService = devServiceMapper.selectDevServiceById(id);
        int ret = 0;
        try {
            if (devService.getServiceParam().indexOf(",") != -1) {
                String[] param = devService.getServiceParam().split(",");
                ret = ShellUtil.execute(devService.getServiceSrc(), param);
            }
        } catch (IOException | InterruptedException e) {
            throw new ServiceException(e.getMessage());
        }
        if (ret == 0) {
            return AjaxResult.success("重启成功");
        } else {
            return AjaxResult.error("重启报错");
        }
    }
}
